<template>
  <div class="update-photo">
      <img :src="img" class="img" ref="img" alt="">
      <div class="toolabr">
          <div class="cancel" @click="$emit('close')">取消</div>
          <div class="confirm" @click="confirm">完成</div>
      </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { updateUserPhoto } from "@/api/user"
export default {
    data(){
        return{
            cropper:null // 裁剪器
        }
    },
    props:{
        img:{
            type:[Object,String],
            required:true
        }
    },
    mounted() {
        const image = this.$refs.img
        // 配置启动插件
        this.cropper = new Cropper(image, {
            viewMode: 1,
            dragMode: 'move',
            aspectRatio: 1,
            autoCropArea: 1,
            cropBoxMovable: false,
            cropBoxResizable: false,
            background: false,
            movable: true
        })
        
    },
    methods:{
        // 确认裁剪
        confirm(){
            // 调用方法获取生成数据
            this.cropper.getCroppedCanvas().toBlob((blob) => {
                // 调用更新生成数据的方法
                this.updatePhoto(blob)
            })
        },
        async updatePhoto(blob){
            this.$toast.loading({
                message:"更新中...",
                forbidClick:true,
                duration:0
            })
            try {
                // 如果接口请求头 Content-Type 是	application/json ，那我们提交js对象数据
                // 如果接口请求头 Content-Type 是	multipart/form-data， 那我们提交 FormData类型
                let fd = new FormData();
                fd.append('photo',blob)
                const { data:res } = await updateUserPhoto(fd); 
                // 关闭弹出层
                this.$emit('close')
                // 更新视图
                this.$emit('update-photo',res.data.photo)
                // 提示成功
                this.$toast.success('更新成功')
            } catch (error) {
                console.log(error);
                this.$toast.fail('更新失败')
            }
        }
    },
    components:{}
}
</script>
<style scoped lang="less">
.update-photo {
    background-color: #000;
    height: 100%;
    .toolabr{
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;
        .cancel,.confirm{
            width: 120px;
            height: 90px;
            font-size: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
        }
    }
    img{
    max-width: 100%;

    }
}
</style>